<template>
  <view :style="{ height: `${props.height}rpx` }">
    <view v-if="props.empty" class="text-#999 flex-center flex-col h-full">
      <i class="i-ph-chart-pie-slice text-180" />
      <text class="mt-2 text-sm">
        暂无数据
      </text>
    </view>
    <mpvue-echarts
      v-else
      ref="chartRef"
      :echarts="echarts"
      :on-init="onInit"
      :canvas-id="canvasId"
      :lazy-load="props.lazyLoad"
      :disable-touch="props.disableTouch"
    />
  </view>
</template>

<script setup lang="ts">

import * as echarts from 'echarts'
import type { EChartsOption, EChartsType } from 'echarts'
import { cloneDeep } from 'lodash-es'
import MpvueEcharts from './mpvue-echarts/echarts.vue'
import { randomAlphabet } from '@/utils/random'
import UEmpty from '@/uni_modules/vk-uview-ui/components/u-empty/u-empty.vue'

const props = withDefaults(defineProps<{
  option: EChartsOption
  lazyLoad?: boolean
  disableTouch?: boolean
  throttleTouch?: boolean
  height?: number
  empty?: boolean
}>(), {
  height: 600,
})

const chartRef = ref<any>()

const canvasId = randomAlphabet(16)

let chart: EChartsType
let scale = 2
let dpr = 2

uni.getSystemInfo({
  success: (res) => {
    dpr = res.pixelRatio
  },
})

const option = computed(() => {
  // 更改Tooltip的位置，处理边界超出的情况
  function setTooltipPosition(point: [number, number], params: any, dom: any, rect: any, size: any) {
    // 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
    // 更改提示框的显示位置
    const x = point[0]//
    const y = point[1]
    // size: 包括 dom 的尺寸和 echarts 容器的当前尺寸，例如：{contentSize: [width, height], viewSize: [width, height]}
    const boxWidth = size.contentSize[0]
    // let boxHeight = size.contentSize[1]; // size里面此处获取不到dom的高度，值为NAN，所以下面指定了一个固定值
    const boxHeight = size.contentSize[1] || 50
    let posX = 0// x坐标位置
    let posY = 0// y坐标位置
    if (x < boxWidth) { // 左边放不开
      posX = 5
    } else { // 左边放的下
      posX = x - boxWidth
    }

    if (y < boxHeight) { // 上边放不开
      posY = 5
    } else { // 上边放得下
      posY = y - boxHeight
    }
    return [posX, posY]
  }
  const option = cloneDeep(props.option)
  if (option.tooltip) {
    if (Array.isArray(option.tooltip)) {
      option.tooltip.forEach((it) => {
        it.position = setTooltipPosition
      })
    } else {
      option.tooltip.position = setTooltipPosition
    }
  }
  return option
})

function onInit(canvas: any, width: number, height: number) {
  chart = echarts.init(canvas, undefined, {
    width, height, devicePixelRatio: dpr,
  })
  canvas.setChart(chart)
  chart.setOption(option.value)
  scale = props.height / height
  return chart
}

watch(() => props.option, async () => {
  if (!chart) {
    return
  }

  chart.resize({
    width: chart.getWidth(),
    height: Math.round(props.height / scale),
  })
  await nextTick()

  chart.setOption(option.value)
})

</script>

<style scoped>

</style>
